<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/26
 * Time: 11:36
 */

namespace app\api\controller;


use app\api\service\Address;
use app\api\service\AfterSale;
use app\api\service\Collection;
use app\api\service\Order;
use app\common\AliPayAccount;
use app\common\Code;
use app\common\Crypt;
use app\common\model\Trade;
use app\common\model\UserAddress;
use app\common\model\UserApplyCash;
use app\common\OrderStatus;
use app\common\Session;

class V4
{
    /**
     * 收藏操作
     * op 操作标识 【del 删除收藏 add 添加收藏】
     * goods_id  商品id
     * community_id  社区id
     */
    function shoucang_edit()
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $community_id = input('community_id');
        if (empty($community_id)) {
            response_json(Code::COMMUNITY_NOT_FOUND);
        }
        if (input('op') == "add") {
            $re = Collection::add([
                "community_id" => $community_id,
                "goods_id" => input('goods_id'),
                "user_id" => $user->id,
                "created_time" => date("Y-m-d H:i:s")
            ]);
            if (!$re) {
                response_json(Code::YI_SHOU_CANG);
            }
        }
        if (input('op') == "del") {
            Collection::del([
                "community_id" => $community_id,
                "goods_id" => input('goods_id'),
                "user_id" => $user->id,
            ]);
        }
        response_json(Code::NONE);
    }

    /**
     * 收藏列表
     * community_id  社区id
     */
    function shoucang_list()
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $community_id = input('community_id');
        if (empty($community_id)) {
            response_json(Code::COMMUNITY_NOT_FOUND);
        }
        $_list = Collection::list_(
            [
                "community_id" => $community_id,
                "user_id" => $user->id,
            ]
        );
        response_json(Code::NONE, $_list);
    }

    /**
     * 地址编辑
     * op 操作标识 【del 删除 edit 添加或者编辑】
     * address_id  【编辑必须传|添加不要传】
     * community_id  社区id【比传】
     *
     * 已下参数是地址信息
     * user_name  联系人
     * telephone  联系人电话
     * address    联系人地址
     */
    function address_edit()
    {
        $user = Session::get_local_user();
        $param = input();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $community_id = input('community_id');
        if (empty($community_id)) {
            response_json(Code::COMMUNITY_NOT_FOUND);
        }
        if (input('op') == "edit") {
            if (
                !isset($param["user_name"]) ||
                !isset($param["telephone"]) ||
                !isset($param["address"])
            ) {
                response_json(Code::PARAM_ERROR);
            }
            if (!isset($param["address_id"])) {
                $param["address_id"] = -1;
            }
            $addr = UserAddress::get($param["address_id"]);
            if (empty($addr)) {
                UserAddress::create([
                    "user_name" => $param["user_name"],
                    "telephone" => $param["telephone"],
                    "address" => $param["address"],
                    "community_id" => $community_id,
                    "user_id" => $user->id,
                    "created_time" => date("Y-m-d H:i:s")
                ]);
            } else {
                UserAddress::update([
                    "address_id" => $param["address_id"],
                    "user_name" => $param["user_name"],
                    "telephone" => $param["telephone"],
                    "address" => $param["address"],
                    "community_id" => $community_id,
                    "user_id" => $user->id,
                ]);
            }
        }
        if (input('op') == "del") {
            UserAddress::destroy([
                "address_id" => input('address_id'),
                "user_id" => $user->id,
            ]);
        }
        response_json(Code::NONE);
    }

    /**
     * 地址列表
     * community_id  社区id
     */
    function address_list()
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $community_id = input('community_id');
        if (empty($community_id)) {
            response_json(Code::COMMUNITY_NOT_FOUND);
        }
        $_list = UserAddress::all([
            "community_id" => $community_id,
            "user_id" => $user->id,
        ]);
        response_json(Code::NONE, $_list);
    }

    /**
     * 设置默认  地址
     *
     * 参数 address_id
     * @param $address_id
     */
    function address_default($address_id = 0)
    {
        if (empty($address_id)) {
            response_json(Code::PARAM_ERROR);
        }
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $user_id = $user->id;
        $addr = new UserAddress();
        $addr->where(["user_id" => $user_id])->update(["default" => 0]);
        $addr->where(["user_id" => $user_id, "address_id" => $address_id])->update(["default" => 1]);
        response_json(Code::NONE);
    }

    /**
     * 订单状态列表
     */
    function order_staus_list()
    {
        $order_status = [
            [
                "ordr_status_id" => 0,
                "title" => "全部"
            ],
            [
                "ordr_status_id" => OrderStatus::DAIFAHUO,
                "title" => "已支付"
            ],
            [
                "ordr_status_id" => OrderStatus::YIJIEDAI,
                "title" => "配送中"
            ],
            [
                "ordr_status_id" => OrderStatus::QUERENSHOUHUO,
                "title" => "已配送"
            ],
            [
                "ordr_status_id" => OrderStatus::BEGIN_AFTER_SALE,
                "title" => "售后"
            ],
        ];
        response_json(Code::NONE, $order_status);
    }

    /**
     * 订单列表
     * 参数
     * order_status_id 不传值是全部订单
     */
    function order_list()
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $param = input();
        $cond = [];
        $cond["shop_order.user_id"] = $user->id;
        if (isset($param["order_status_id"]) && $param["order_status_id"] > 0) {
            $cond["order_status_id"] = $param["order_status_id"];
        }
        $orders = Order::list_($cond);
        response_json(Code::NONE, $orders);
    }

//    /**
//     * 确认收货
//     * 参数
//     * order_id
//     * pwd
//     */
//    function order_querenshouhuo()
//    {
//        $user = Session::get_local_user();
//        if (empty($user)) {
//            response_json(Code::NO_LOGIN);
//        }
//        $fund = $user->getUserFund();
//        $param = input();
//        if (!isset($param["order_id"]) || !isset($param["pwd"])) {
//            response_json(Code::PARAM_ERROR);
//        }
//        if (Crypt::pwd($param["pwd"]) != $fund->password) {
//            response_json(Code::YUE_PWD_ERROR);
//        }
//        $cond = [];
//        $cond["shop_order.user_id"] = $user->id;
//        $cond["shop_order.order_id"] = $param["order_id"];
//        $cond["shop_order.order_status_id"] = ["<=", OrderStatus::QUERENSHOUHUO];
//        $order = Order::order($cond);
//        if ($order instanceof \app\common\model\Order) {
//            OrderStatus::querenshouhuo($order);
//            response_json(Code::NONE, $order);
//        } else {
//            response_json(Code::FAIL);
//        }
//    }

    /**
     * 订单详情
     * 参数
     * order_id  订单id
     */
    function order_item()
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $param = input();
        $cond = [];
        $cond["shop_order.user_id"] = $user->id;
        if (isset($param["order_id"]) && $param["order_id"] > 0) {
            $cond["order_id"] = $param["order_id"];
        }
        $orders = Order::order($cond);
        response_json(Code::NONE, $orders);
    }

    /**
     * 申请提现
     * 参数
     * value  申请金额
     * apply_memo 备注
     */
    function apply_cash($value = 0)
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $cash = UserApplyCash::get([
            "user_id" => $user->id,
            "status" => 0,
        ]);
        if ($cash) {
            response_json(Code::FAIL, [], "您的上一笔提现申请还未审核");
        }
        $user->getUserFund();
        #@todo   判断 ali_account 有效
        UserApplyCash::create([
            "created_time" => date("Y-m-d H:i:s"),
            "user_id" => $user->id,
            "apply_memo" => input('apply_memo'),
            "value" => $value,
        ]);
        response_json(Code::NONE);
    }

    /**
     * 用户余额
     */
    function fund_info()
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $fund = $user->getUserFund();
        response_json(Code::NONE, [
            "fee" => isset($fund->value) ? $fund->value : 0
        ]);
    }


    /**
     * <span style="color:#f00;">交易类型列表</span>
     */
    function  trade_type_list(){
        response_json(Code::NONE, [
            [
                "trade_type"=>0,
                "des"=>"全部",
            ],
            [
                "trade_type"=>Trade::TRADE_SHOP,
                "des"=>"购物",
            ],
            [
                "trade_type"=>Trade::TRADE_CUSTORMER,
                "des"=>"售后",
            ],
            [
                "trade_type"=>Trade::TRADE_RECHARGE,
                "des"=>"充值",
            ],
            [
                "trade_type"=>Trade::TRADE_TIXIAN,
                "des"=>"提现",
            ],
            [
                "trade_type"=>Trade::TRADE_FANLI,
                "des"=>"返利",
            ]
        ]);
    }
    /**
     * 账单列表
     * 【接口返回的全部数据】
     * 参数
     * trade_type  交易类型
     */
    function  trade()
    {
        $trade_type = input('trade_type');
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $fund = $user->getUserFund();
        $trade = new Trade();
        $trade->order("id desc")
            ->where(["user_id" => $user->id]);
        if (!empty($trade_type)) {
            $trade->where(["trade_type" => $trade_type]);
        }
        $trade_data = $trade->paginate();
        response_json(Code::NONE, [
            "trade_data" => $trade_data,
            "user_fund" => $fund->value
        ]);
    }

    /**
     * 提交  售后
     * 参数两个
     * @param int $order_id
     * @param string $memo
     */
    function after_sale_add($order_id = 0, $memo = '')
    {
        if (session("after_sale_list") && session("after_sale_list") - time() > 30) {
            response_json(Code::FREQUENTLY);
        }
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        /** @var \app\common\model\Order $order */
        $order = Order::order(["order_id" => $order_id]);
        if (empty($order) || $order->user_id != $user->id) {
            response_json(Code::ORDER_EMPTY);
        } else {
            OrderStatus::begin_after_sale($order);
            $af_sale = \app\common\model\AfterSale::get(["order_id" => $order->order_id]);
            if (empty($af_sale)) {
                AfterSale::save_($order, $memo);
            } else {
                $af_sale->memo = $memo;
                $af_sale->save();
            }
            session("after_sale_list", time());
            response_json(Code::NONE);
        }
    }

//    /**
//     * 我的售后
//     * 参数
//     * page 分页
//     */
//    function after_sale_list()
//    {
//        $user = Session::get_local_user();
//        if (empty($user)) {
//            response_json(Code::NO_LOGIN);
//        }
//        AfterSale::list_($user);
//    }

    /**
     * 绑定支付宝账号
     * 参数：
     * @param string $payee_account
     * @param string $real_name
     */
    function bind_ali_account($payee_account = '', $real_name = '')
    {

        if (empty($payee_account) || empty($real_name)) {
            response_json(Code::PARAM_ERROR);
        }
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $fund = $user->getUserFund();
        $ali_a = new AliPayAccount($payee_account, $real_name);
        $fund->save([
            "alipay_account" => $ali_a
        ]);
        response_json(Code::NONE);

    }

    /**
     * 获取阿里账户
     */
    function get_ali_account()
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $fund = $user->getUserFund();
        $ali_a = AliPayAccount::build_by_json($fund->alipay_account);
        response_json(Code::NONE, $ali_a);

    }


}